require 'open-uri'
require 'mysql2'

mysql_client=Mysql2::Client.new(:host => "127.0.0.1", :username => "dev",:password=>"justsoso123",:database=>"xdouban")

results=mysql_client.query("select thumb_url from photo where download=0 and id>=370")

results.each do |hash|

	thumb_url=hash['thumb_url']
	puts thumb_url

	if thumb_url.empty?
		next
	end

	url=thumb_url.sub("/thumb/","/photo/")

	if url.end_with?("photo_album.png")
		puts "default cover,ignore"
		next
	end
	
	puts "fetch #{url}"
	begin

		open(url) do |fin|
		  size = fin.size
		  download_size = 0
		  puts "size: #{size}"
		  filename = url[url.rindex('/')+1, url.length-1]

		  dir=filename[0,filename.rindex('.')][-1]

		  puts "name: #{filename}"
		  open("./photo/#{dir}/"+File.basename("./#{filename}"),"wb") do |fout|
		     while buf = fin.read(1024) do
			       fout.write buf
		       download_size += 1024
		       print "Downloaded #{download_size * 100 / size}%\r"
		       STDOUT.flush 
		    end
		  end
		end

	       sleep(4)

	rescue Exception
		puts "Failed get #{url}    :#{$!}"
	end
	

end

